/*
 * @Author: zyk 997610780@qq.com
 * @Date: 2022-10-31 10:37:32
 * @LastEditors: zyk 997610780@qq.com
 * @LastEditTime: 2022-11-01 14:19:29
 * @FilePath: \fifty-small-projects\49模糊搜索\49.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
let search_record_box = document.querySelector('.search_record')
let search_box = document.querySelector('.search_box')
let search_input = document.querySelector('.search_input')
let search_record = getRecord() || []
updateListDOM()
search_box.addEventListener('submit',(e)=>{
  e.preventDefault()
  addRecord()
  search_input.value = ""
})

search_input.addEventListener('input',()=>{
  dimFilter(search_input.value)
})

function getRecord(){
  let list = window.localStorage.getItem('todos')
  return JSON.parse(list)
}


function addRecord(){
  if(search_input.value ){
    if(!search_record.some(item => item == search_input.value)){
      search_record.unshift(search_input.value)
      localStorage.setItem('todos',JSON.stringify(search_record))
    }
  }
  updateListDOM()
}


function updateListDOM(list){
  let records = search_record
  if(list && list.length){
    records = list
  }
  search_record_box.innerHTML = ''
  records.forEach((item, index) => {
    let record_item = document.createElement('div')
    record_item.classList.add('record_item')
    record_item.innerText = item
    record_item.addEventListener('click',()=>{
      search_input.value = item
      dimFilter(item)
    })
    record_item.addEventListener('contextmenu',(e)=>{
      e.preventDefault()
      search_record = getRecord().filter(e=>e != item)
      localStorage.setItem('todos', JSON.stringify(search_record))
      record_item.remove()
    })
    search_record_box.appendChild(record_item)

  })
}


function dimFilter(v){
  let list = search_record.filter(item => item.includes(v))
  updateListDOM(list)
}
